<template>
  <BaseChart :options="chartOptions" @chart-ready="onChartReady" @refresh="$emit('refresh')" />
</template>

<script setup>
import { computed } from 'vue'
import BaseChart from './BaseChart.vue'

const props = defineProps({
  data: {
    type: Object,
    default: () => ({})
  },
  height: {
    type: String,
    default: '400px'
  },
  config: {
    type: Object,
    default: () => ({})
  },
  showEmpty: {
    type: Boolean,
    default: true
  }
})

const emit = defineEmits(['chartReady', 'refresh'])

// 获取饼图配置
const pieOption = computed(() => props.config.option || {})

// 检查是否有有效数据
const hasValidData = computed(() => {
  const nameField = pieOption.value.nameField
  const valueField = pieOption.value.valueField

  if (!nameField || !valueField) {
    return false
  }

  const data = props.data || {}
  const nameData = data[nameField]
  const valueData = data[valueField]

  return nameData && Array.isArray(nameData) && nameData.length > 0 &&
    valueData && Array.isArray(valueData) && valueData.length > 0
})

const chartOptions = computed(() => {
  const data = props.data || {}
  const nameField = pieOption.value.nameField
  const valueField = pieOption.value.valueField

  if (!hasValidData.value) {
    return {
      title: {
        text: props.config.title || '饼图',
        left: 'center'
      },
      series: []
    }
  }

  const nameData = data[nameField] || []
  const valueData = data[valueField] || []

  // 构建饼图数据
  const pieData = nameData.map((name, index) => {
    const value = valueData[index] || 0
    return {
      name: name,
      value: value
    }
  })

  // 格式化数字
  const formatNumber = (value) => {
    if (pieOption.value.decimalPlaces > 0) {
      return value.toFixed(pieOption.value.decimalPlaces)
    }
    return value.toString()
  }

  return {
    title: {
      text: props.config.title || '饼图',
      left: 'center',
      textStyle: {
        fontSize: 16,
        fontWeight: 'bold'
      }
    },

    legend: {
      orient: 'vertical',
      left: 'left',
      top: 'middle'
    },

    series: [
      {
        name: props.config.title || '数据',
        type: 'pie',

        data: pieData,
        label: {
          show: pieOption.value.showLabel,
          fontSize: pieOption.value.fontSize,
          formatter: (params) => {
            const value = formatNumber(params.value)
            if (pieOption.value.showPercentage) {
              return `${params.name}\n${value} (${params.percent}%)`
            }
            return `${params.name}\n${value}`
          }
        },
        itemStyle: {
          color: (params) => {
            return pieOption.value.colors?.[params.dataIndex % pieOption.value.colors.length] || '#5470c6'
          }
        },
        emphasis: {
          itemStyle: {
            shadowBlur: 10,
            shadowOffsetX: 0,
            shadowColor: 'rgba(0, 0, 0, 0.5)'
          }
        }
      }
    ]
  }
})

const onChartReady = (chart) => {
  emit('chartReady', chart)
}

// 暴露字段给父组件
const arrayFields = computed(() => {
  const data = props.data || {}
  return Object.keys(data).filter(key =>
    Array.isArray(data[key]) && data[key].length > 0
  )
})

defineExpose({
  arrayFields
})
</script>